#!/usr/bin/env python
# coding: utf-8

"""
云片api短信发送
"""

import http.client
import urllib.parse
import json
import datetime
from conf.settings import YUNPIAN
from utility.log import Logger

logger = Logger().get_logger()


class YunPian:
    def __init__(self):
        self.apikey = YUNPIAN['key']
        self.url = YUNPIAN['url']
        self.host = YUNPIAN['host']
        self.port = YUNPIAN['port']
        self.headers = {"Content-type": "application/x-www-form-urlencoded",
                        "Accept": "text/plain"}

    def encode_args(self, args):
        """格式化自定义参数为字符串
        """
        return urllib.parse.urlencode(args)

    def tpl_send(self, mobile, tpl, args, timeout=5):
        '''
        调用云片api发送模板短信
        tpl: 模板名称
        args：模板参数
        '''
        hour = datetime.datetime.now().hour
        key = 'msg_times_%s_%s' % (mobile, hour)
        # if not self.check_send_times(mobile, key):
        #     return "limit"
        conn = http.client.HTTPConnection(self.host, port=self.port, timeout=30)
        parmas = {
            "apikey": self.apikey,
            "mobile": mobile,
            "tpl_id": tpl,
            "tpl_value": args,
        }
        data = self.encode_args(parmas)
        status = 'success'
        try:
            conn.request("POST", self.url['tpl'], data, headers=self.headers)
            response = conn.getresponse()
            result = json.loads(response.read())
            if result['code'] == 0:
                logger.info('Send tpl msg to %s success by yunpian api' % mobile)
            else:
                status = 'error'
                logger.error('Send tpl msg to %s fail by yunpian api，code %s'
                        % (mobile, result['code']))
            # self.set_send_times(key)
            conn.close()
        except Exception as e:
            status = "error"
            error_info = str(e)
            logger.error('Send tpl msg to %s fail by yunpian api，error info: %s'
                    % (mobile, error_info))

        return status

    def normal_send(self, mobile, text, timeout=5):
        """调用云片api智能匹配模板发送
        """
        hour = datetime.datetime.now().hour
        key = 'msg_times_%s_%s' % (mobile, hour)
        # if not self.check_send_times(mobile, key):
        #     return "limit"
        conn = http.client.HTTPConnection(self.host, port=self.port, timeout=30)
        parmas = {
            "apikey": self.apikey,
            "mobile": mobile,
            "text": text,
        }
        data = self.encode_args(parmas)
        status = 'success'
        try:
            conn.request("POST", self.url['normal'], data,
                         headers=self.headers)
            response = conn.getresponse()
            _res = response.read()
            result = json.loads(_res.decode())
            if result['code'] == 0:
                logger.info('Send normal msg to %s success by yunpian api'
                         % mobile)
            else:
                status = 'error'
                logger.error('Send normal msg to %s fail by yunpian api，code %s'
                        % (mobile, result['code']))
            # self.set_send_times(key)
            conn.close()
        except Exception as e:
            status = "error"
            error_info = str(e)
            logger.error('Send normal msg to %s fail by yunpian api，error info: %s'
                    % (mobile, error_info))

        return status

    def normal_send_with_no_limit(self, mobile, text, timeout=5):
        """
        无限制调用云片api智能匹配模板发送
        """
        conn = http.client.HTTPConnection(self.host, port=self.port, timeout=30)
        parmas = {
            "apikey": self.apikey,
            "mobile": mobile,
            "text": text,
        }
        data = self.encode_args(parmas)
        status = 'success'
        try:
            conn.request("POST", self.url['normal'], data,
                         headers=self.headers)
            response = conn.getresponse()
            result = json.loads(response.read())
            if result['code'] == 0:
                logger.info('Send normal msg to %s success by yunpian api'
                         % mobile)
            else:
                status = 'error'
                logger.error('Send normal msg to %s fail by yunpian api，code %s'
                        % (mobile, result['code']))
            conn.close()
        except Exception as e:
            status = "error"
            error_info = str(e)
            logger.error('Send normal msg to %s fail by yunpian api，error info: %s'
                    % (mobile, error_info))

        return status

    # def check_send_times(self, mobile, key):
    #     """限制同一号码发送次数，每小时只能发送6次
    #     """
    #     times = captcha_redis.get(key)
    #     times = times.decode() if isinstance(times, bytes) else times
    #     try:
    #         if times and int(times) >= 6:
    #             logger.error('Send normal msg to %s fail，send times limit' % mobile)
    #             return False
    #     except:
    #         return False
    #     return True

    # def set_send_times(self, key):
    #     """设置号码每小时发送次数，过期时间1小时
    #     """
    #     send_times = captcha_redis.get(key)
    #     send_times = send_times.decode() if isinstance(send_times, bytes) else send_times
    #     send_times = 1 if not send_times else int(send_times) + 1
    #     captcha_redis.setex(key, send_times, 3600)


if __name__ == "__main__":
    # 测试将手机号改为自己手机号进行测试
    mobile = '15228873470'
    yunpian = YunPian()
    text = "您的验证码是7861【知道创宇云安全】"
    tpl = 992285
    args = '#domain#=test.com'
    yunpian.normal_send(mobile, text)
    yunpian.tpl_send(mobile, tpl, args)
